using Flurl.Http;
using Vin.Extension.Alibaba.Market.Models;
using Vin.Extension.Alibaba.Market.Options;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Attributes;
using Vin.Tool.Core.JsonCategory;
using Vin.Tool.Domain.ExceptionModel;

namespace Vin.Extension.Alibaba.Market.Services;

/// <summary>
/// 身份证验证服务
/// </summary>
public class IdCardCheckService : VinBaseSingletonService
{
    private IdCardCheckOption _idCardCheckOption => VinApp.GetOption<IdCardCheckOption>();

    /// <summary>
    /// 身份证验证
    /// </summary>
    /// <param name="name">姓名</param>
    /// <param name="idcard">身份证</param>
    /// <returns></returns>
    public async Task<(bool, string)> CheckAsync(string name, string idcard)
    {
        if (!_idCardCheckOption.CheckHaveBase) return (false, "请配置身份证验证服务的相关参数节点：Alibaba:Market:IdCardCheck");
        if (string.IsNullOrWhiteSpace(name)) throw new BusinessException("姓名不能为空");
        if (string.IsNullOrWhiteSpace(idcard)) throw new BusinessException("身份证不能为空");

        var resData = await _idCardCheckOption.BaseUrl
            .WithHeader("Authorization", "APPCODE " + _idCardCheckOption.AppCode)
            .PostUrlEncodedAsync(new
            {
                name,
                idcard
            })
            .ReceiveString();
        var model = resData.ToCamelCaseObject<IdCardCheckModel>();
        if (model == null) return (false, "身份证验证服务返回数据为空");
        return model.IsSuccess();
    }
}